import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizProduct from '@/views/biz/bizorder/modules/BizProduct'
import BizOrderPlanForm from '@/views/biz/bizorder/modules/BizOrderPlanForm'
import { getBizOrder, addBizOrder, updateBizOrder, delBizOrder,getProcessDetail,processOrder } from '@/api/biz/bizOrder'
import { listBizOrderProcessRecord,updateProcess } from '@/api/biz/bizOrderProcessRecord'
import {listBizOrderProduct } from '@/api/biz/bizOrderProduct'
import { upload } from '@/api/system/upload'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import ProcessAddForm from '@/views/biz/bizprocessplan/modules/ProcessAddForm'
import SelectUser from '@/views/biz/bizorder/modules/SelectUser';
import BizProductSetProcess from './BizProductSetProcess'
export default {
  name: 'CreateForm',
  components: {
    AntModal,
    BizOrderPlanForm,
    AdvanceTable,
    ProcessAddForm,
    SelectUser,
    BizProductSetProcess
  },
  mixins:[tableDragResizeMixin],
  data() {
    return {
      showProductModal: false,
      disabledCreated:false,
      showPlanModal: false,
      showAddSubModal:false,
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      activeKey: "1",
      id: undefined,
      formTitle: '添加销售单',
      // 表单参数
      form: {},
      attachmentRefName: 'addUploaderFile', // 标志表单是否含有附件
      formId: '',
      productList:[],
      processList:[],
      currentSearch:{},
      currentSearchIndex:0,
      multiple:false,
      currentIndex:0,
      searchIndex:0,
      showSetUser:false,
      showProcessModal:false,
      rules: {
        customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
        orderType: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }]
      },
      columns: [
        {
          title: '品牌',
          dataIndex: 'brand',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '区域',
          dataIndex: 'area',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
          width: '12.8%'
        },
        {
          title: '备注',
          align: 'center',
          width: '12.8%'
        }
      ],
      columns1: [
        {
          title: '工序名称',
          ellipsis: true,
          align: 'center',
          width: '12.8%',
          dataIndex:'processName',
          scopedSlots: {
            customRender: 'processName'
          }
        },
        {
          title: '计划量',
          ellipsis: true,
          align: 'center',
          width: '12.8%',
          dataIndex:'processVol',
          scopedSlots: {
            customRender: 'processVol'
          }
        },
        {
          title: '单价',
          dataIndex: 'unitSalary',
          align: 'center',
          width: '12.8%',
          scopedSlots: {
            customRender: 'unitSalary'
          }
        },
        {
          title: '排序',
          ellipsis: true,
          align: 'center',
          width: '8%',
          dataIndex:'sortNumber',
          scopedSlots: {
            customRender: 'sortNumber'
          }
        },
        {
          title: '备注',
          ellipsis: true,
          align: 'center',
          width: '12.8%',
          dataIndex:'remark',
          scopedSlots: {
            customRender: 'remark'
          }
        },
      ],
      columns2: [
        {
          title: '产品编号',
          dataIndex: 'productCode',
          ellipsis: true,
          align: 'left',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '数量(片)',
          dataIndex: 'number2',
          align: 'right',
          width: '12.8%',
          scopedSlots: {
            customRender: 'number2Slot'
          }
        },
        {
          title: '数量(米)',
          dataIndex: 'number3',
          align: 'right',
          width: '12.8%'
        },
        {
          title: '数量(平米)',
          dataIndex: 'number4',
          align: 'right',
          width: '12.8%'
        }
      ],
      columns3:[
        {
          title: '品牌',
          dataIndex: 'brand',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          ellipsis: true,
          align: 'center',
          width: '12.8%'
        },
        {
          title: '数量',
          dataIndex: 'number',
          align: 'center',
          width: '12.8%'
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          width: '12.8%'
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'center',
          width: '12.8%'
        },
        {
          title: '备注',
          align: 'center',
          width: '12.8%'
        }
      ],
      columns4:[
        {
          title: '工序名称',
          ellipsis: true,
          align: 'center',
          width: '8%',
          dataIndex:'processName',
        },
        {
          title: '操作员',
          ellipsis: true,
          align: 'center',
          width: '12.8%',
          dataIndex:'createByName',
          scopedSlots: {
            customRender: 'createByName'
          }
        },
        {
          title: '计划量',
          ellipsis: true,
          align: 'center',
          width: '8%',
          dataIndex:'processVol',
          scopedSlots: {
            customRender: 'processVol'
          }
        },
        {
          title: '单位',
          ellipsis: true,
          align: 'center',
          width: '6%',
          dataIndex:'unitName',
          scopedSlots: {
            customRender: 'unitName'
          }
        },
        {
          title: '完工情况',
          ellipsis: true,
          align: 'center',
          width: '8%',
          dataIndex:'completedVol',
          scopedSlots: {
            customRender: 'completedVol'
          }
        },
        {
          title: '排序',
          ellipsis: true,
          align: 'center',
          width: '8%',
          dataIndex:'sortNumber',
          scopedSlots: {
            customRender: 'sortNumber'
          }
        },
        {
          title: '备注',
          ellipsis: true,
          align: 'center',
          dataIndex:'remark',
          scopedSlots: {
            customRender: 'remark'
          }
        }
      ],
      list: [],
      selectedRowKeys: [],
      ids: [],
      fileList: []
    }
  },
  filters: {},
  created() { 
    this.initColumnsSetting('produceProductDetail')
    this.initColumnsSetting('produceProcessDetail','columns1')
    this.initColumnsSetting('editProductDetail','columns3')
    this.initColumnsSetting('editProcessDetail','columns4')
    
  },
  computed: {},
  watch: {},
  mounted() { },
  methods: {
    onClose() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    
    getRowClassName(row,index){
      if (index === this.currentIndex) {
        return 'selected_table_row'
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset() {
      this.form = {}
    },
    getList() {
      this.open = false
      this.$emit('close')
      this.$emit('ok')
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open = true
      this.formTitle = row.id ? '添加销售单' : '新增销售单';
      this.form = row
      if (row.id) {
        this.form.biller = { ids: row.biller, names: row.billerName }
        this.form.attachList.forEach((item,index) => {
          const d = {
            uid: index,
            name: item,
            url: item,
            status: 'done'
          }
          // 文件列表
          this.fileList.push(d)
        })
      }
    },
    handleProduce(row){
      this.reset()
      this.open = true
      this.formTitle = '下达生产';
      this.form = row
      this.loading = true
      getProcessDetail(row.id).then(res=>{
        this.loading = false
        if(res.code == 200) {
           this.productList = (res.data || [])//.filter(v=>v.in)//只保留参与库存计算的
            if(this.productList.length){
              this.processList = this.productList.map(v=>v.bizProductionProcessList)
              console.log('this.processList :>> ', this.processList);
              this.processList.forEach((val,index)=>{
                this.$set(val,'sortNumber',index + 1)
                this.getCurrentList(index)
              })
            }
         }else{
           this.message.error(res.msg)
         }
      }).catch(()=>{
        this.loading = false
      })
    },
    async handleProduceEdit(row){
      this.reset()
      this.open = true
      this.formTitle = '编辑工序';
      this.form = row
      this.currentIndex = 0
      await this.getProductList()
      this.getProcessList()
    },
    completedVolChange(value,record,index){
      this.$forceUpdate()
    },
    handleDeleteRows() {
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.processList[this.currentIndex] = this.processList[this.currentIndex].filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.id))
          this.selectedRowKeys = []
          console.log('processList :>> ', this.processList);
          this.multiple = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    
    onSearch(row,index) {
      this.searchIndex  = index 
      this.showSetUser = true
      this.$nextTick(() => (
        this.$refs.selectUserRef.showSelectUser(this.deptId)
      ))
    },  
    /**
     * 确认选择用户
     * @param {*} user 
     */
    saveSelectUser(user) {
      let item = this.processList[this.currentIndex][this.searchIndex]
      item.createByName = user.names
      item.creator = user.ids
      this.processList[this.currentIndex].splice(this.searchIndex,1,item)
      this.showSetUser = false
    },
    handleAddProcess(){
      this.processList[this.currentIndex].push({processVol:this.productList[this.currentIndex].number})
      this.$forceUpdate()
    },
    /**
     * 选择工序
     */
    onSearchProcess(record,index){
      this.showAddSubModal = true
      // this.currentSearch  = record
      // this.currentSearchIndex = index
      this.$nextTick(()=>{
        this.$refs.processAddForm.handleSetProcess()
      })
    },
    onSearchPlan(record,index){
      this.showProcessModal = true;
      this.$nextTick(()=>{
        this.$refs.bizProductSetProcess.handleSetProcess(this.productList[this.currentIndex])
      })
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      let arr = []
      this.processList.forEach(childArr=>{
        childArr.forEach(val=>{
          arr.push(val)
        })
      })
      let param ={
        id:this.form.id,
        recordList:arr
      }
      this.loading = true
      processOrder(param).then(res=>{
        this.loading = false
        if(res.code == 200) {
           this.$message.success('操作成功')
           this.open = false
           this.$emit('ok')
         }else{
           this.message.error(res.msg)
         }
      }).catch(()=>{
        this.loading = false
      })
    },
    /** 提交按钮 */
    submitEditForm: function (closeDialog) {
      console.log('this.processList :>> ', this.processList);
      let arr = this.processList.map((v,idx)=>{
        let obj ={
          id:this.productList[idx].id,
          orderId:this.form.id,
          recordList:v.map(val=>(val.orderId=this.form.id,val))
        }
        return obj
      })
      arr = arr.filter(v=>v)
      this.loading = true
      updateProcess(arr).then(res=>{
        this.loading = false
        if(res.code == 200) {
           this.$message.success('操作成功')
           this.open = false
           this.$emit('ok')
         }else{
           this.message.error(res.msg)
         }
      }).catch(()=>{
        this.loading = false
      })
    },
    selectProcess(selectedRows){
      selectedRows.forEach(val=>{
        val.number = this.productList[this.currentIndex].number
      })
      let arr = selectedRows.map(v=>{
        let item = {
          processVol: this.productList[this.currentIndex].number,
          unitSalary: v.unitSalary,
          processCode:v.processCode,
          processName:v.processName,
          productId:this.productList[this.currentIndex].productId,//11
          processPlanId:this.productList[this.currentIndex].planId,
          processId:v.id,
          unit:this.productList[this.currentIndex].unit,
          sortNumber:v.sortNumber,
          orderProductId:this.productList[this.currentIndex].id//产品明细id
        }
        return item
      })
      this.processList[this.currentIndex].push(...arr)
      this.$forceUpdate()
    },
    selectProcessByPlan(selectedRows){
      this.processList[this.currentIndex] = []
      this.selectProcess(selectedRows)
    },
    selectEditProcess(selectedRows){
      selectedRows.forEach(val=>{
        val.number = this.productList[this.currentIndex].number
      })
      let arr = selectedRows.map(v=>{
        let item = {
          processVol: this.productList[this.currentIndex].number,
          unitSalary: v.unitSalary,
          processCode:v.processCode,
          processName:v.processName,
          productId:this.productList[this.currentIndex].productId,//11
          processPlanId:this.productList[this.currentIndex].planId,
          processId:v.id,
          unit:this.productList[this.currentIndex].unit,
          sortNumber:v.sortNumber,
          orderProductId:this.productList[this.currentIndex].id//产品明细id
        }
        item.unitList = []
        item.unitList.push({
          key: '1',
          name: this.productList[this.currentIndex].unitA
        })
        item.unitList.push({
          key: '2',
          name: this.productList[this.currentIndex].unitB
        })
        item.unitList.push({
          key: '3',
          name: this.productList[this.currentIndex].unitC
        })
        return item
      })
      this.processList[this.currentIndex].push(...arr)
    },
    back() {
      const index = '/biz/bizorder/index'
      this.$router.push(index)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    handleSubDelete(row) {
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          let selectedList = JSON.parse(JSON.stringify(that.list));
          selectedList.forEach((item, index) => {
            if (row.id) {
              that.list = that.list.filter(item => item.id != row.id)
              return;
            } else {
              that.selectedRows.forEach(item2 => {
                that.list = that.list.filter(item => item.id != item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel() { }
      })
    },
    handleAddProduct() {
      this.showProductModal = true
      this.$nextTick(() => {
        this.$refs.bizProduct.handleAddProduct(this.list);
      })
    },
    selectProduct(selectedRows) {
      this.list = selectedRows;
      //修改单位
      this.list.forEach(item => {
        item.number = 0;
        item.tempSalePrice = item.salePrice;
        if (item.defaultOutboundUnit == 2) {
          item.unit = 2
          item.number2 = item.number * item.convertRatioA;
          item.salePrice = item.salePriceA
        } else if (item.defaultOutboundUnit == 3) {
          item.unit = 3
          item.salePrice = item.salePriceB
          item.number2 = item.number * item.convertRatioB;
        } else {
          item.unit = 1;
          item.number2 = item.number;
        }
        item.amount = 0.00;
        item.unitList = [];
        item.unitList.push({
          key: 1,
          name: item.unit
        })
        item.unitList.push({
          key: 2,
          name: item.assistUnitA
        })
        item.unitList.push({
          key: 3,
          name: item.assistUnitB
        })
        item.number3 = item.number2 * item.convertRatioA;
        item.number4 = item.number2 * item.convertRatioB;
      })
    },
    changePlan(record){
      let res = this.form.planOptions.filter(item => item.id == record.planId);
      record.processCode = res[0].processCode
      record.standardHours = res[0].standardHours
      record.unitSalary = res[0].unitSalary
      this.$forceUpdate();
    },
    changeUnit(record) {
      if (record.unit == 1) {
        record.salePrice = record.tempSalePrice;
      } else if (record.unit == 2) {
        record.salePrice = record.salePriceA;
      } else if (record.unit == 3) {
        record.salePrice = record.salePriceB;
      }
      this.changeNumber(record);
    },
    changeNumber(record) {
      record.amount = record.salePrice * record.number;
      this.$forceUpdate();
      if (record.unit == 1) {
        record.number2 = record.number;
      } else if (record.unit == 2) {
        record.number2 = (record.number / record.convertRatioA).toFixed(3);
      } else if (record.unit == 3) {
        record.number2 = (record.number / record.convertRatioB).toFixed(3);
      }
      this.changeNumber2(record);
    },
    changeNumber2(record) {
      record.number3 = (record.number2 * record.convertRatioA).toFixed(3);
      record.number4 = (record.number2 * record.convertRatioB).toFixed(3);
      this.$forceUpdate();
    },
    handleChange(info,e) {
      const formData = new FormData();
      formData.append('file', info.file);
      upload(formData).then(response => {
          const d = {
          uid: info.file.uid,
          name: response.fileName,
          url: response.url,
          status: 'done'
        }
        this.fileList.push(d);
      })
    },
    handleRemove(info) {
      this.fileList = this.fileList.filter(function (item) {
        return item.uid != info.uid
      })
    },
    getCurrentList(index){
      this.processList[index] = this.processList[index].map(v=>{
        let item = {
          processVol: this.productList[index].number,
          productId:this.productList[index].productId,
          processPlanId:v.planId,
          processId:v.id,
          unit:this.productList[index].unit,
          orderProductId:this.productList[index].id,

         // ---
          unitSalary: v.unitSalary,
          processCode:v.processCode,
          processName:v.processName,
          sortNumber:v.sortNumber,
        }
        return item
      })
    },
    getProductList() {
      return new Promise((resolve, reject) => {
        this.loading = true
        let param = {
          pageNum: 1,
          pageSize: 1000,
          orderId: this.form.id
        }
        listBizOrderProduct(param).then(res => {
          this.loading = false
          if(res.code == 200) {
            this.productList = res.data.list
            resolve()
          }else{
            this.message.error(res.msg)
            reject()
          }
        }).catch(()=>{
          this.loading = false
          reject()
        })
      })
    },
    getProcessList(){
      // 工序
      let param = {
        orderId:this.form.id,
        productId:this.productList[this.currentIndex].productId,
        orderProductId:this.productList[this.currentIndex].id
      }
      this.loading = true
      listBizOrderProcessRecord(param).then(res=>{
        this.loading = false
        if(res.code == 200) {
          let arr = res.data.list
          arr = arr.map(v=>{
            v.unitList = []
            v.unitList.push({
              key: '1',
              name: this.productList[this.currentIndex].unitA
            })
            v.unitList.push({
              key: '2',
              name: this.productList[this.currentIndex].unitB
            })
            v.unitList.push({
              key: '3',
              name: this.productList[this.currentIndex].unitC
            })
            return v
          })
          this.processList[this.currentIndex] = res.data.list
          console.log('this.processList :>> ', this.processList);
        }else{
          this.message.error(res.msg)
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    customRow (record,index) {
      return {
        on: {
          click: () => {
            this.$nextTick(() => {
              this.currentIndex = index
            })
          }
        }
      }
    },
    customEditRow (record,index) {
      return {
        on: {
          click: () => {
            this.$nextTick(() => {
              this.currentIndex = index
              this.getProcessList()
            })
          }
        }
      }
    },

  }
}
